package com.taotao.search.mq.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.search.bean.Item;
import com.taotao.search.service.ItemService;

public class ItemMQHandler {


	@Autowired
	private HttpSolrServer httpSolrServer;
	
	@Autowired
	private ItemService itemService;
	
	private static final ObjectMapper MAPPER = new ObjectMapper();
	/**
	 * 接收商品变更消息处理
	 * 	新增、修改：更新solr的数据信息
	 * 	删除  --- 删除solr的数据
	 * <p>Title: execute</p>
	 * <p>Description: </p>
	 * @param jsonMsg
	 */
	public void execute(String jsonMsg) {
		try {
			JsonNode jsonNode = MAPPER.readTree(jsonMsg);
			Long itemId = jsonNode.get("itemId").asLong();
			String type = jsonNode.get("itemId").asText();
			
			if(StringUtils.equals(type, "delete")) {
				httpSolrServer.deleteById(String.valueOf(itemId));
			}else if(StringUtils.equals(type, "insert")||StringUtils.equals(type, "update")){
				Item item = this.itemService.getItemById(itemId);
				httpSolrServer.addBean(item);
			}
			httpSolrServer.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}
